//
//  SkyAssociationMenuView.m
//
//  Created by skytoup on 14-10-24.
//  Copyright (c) 2014年 skytoup. All rights reserved.
//
#import "twolevelTableViewCell.h"
#import "firstlevelTableViewCell.h"
#import "SkyAssociationMenuView.h"

NSString *const IDENTIFIER = @"CELL";

@interface SkyAssociationMenuView () <UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate>
{
    NSArray *tables;
    UIView *bgView;
}
@end

@implementation SkyAssociationMenuView

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    NSAssert(false, @"cann't not use - initWithCoder:, please user - init");
    return nil;
}

- (instancetype)init{

//    self = [super initWithFrame:frame];
    if (self= [super init]) {
        // 初始化选择项
        for(int i=0; i!=3; ++i) {
            sels[i] = -1;
        }
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight);
        self.userInteractionEnabled = YES;
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.frame = self.frame;
        [cancelBtn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:cancelBtn];
        // 初始化菜单
        tables = @[[[UITableView alloc] init], [[UITableView alloc] init], [[UITableView alloc] init] ];
        [tables enumerateObjectsUsingBlock:^(UITableView *table, NSUInteger idx, BOOL *stop) {
            [table registerClass:[UITableViewCell class] forCellReuseIdentifier:IDENTIFIER ];
              table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

            table.dataSource = self;
            table.delegate = self;
            table.bounces = NO;
            table.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight);
            
            
            if (idx==0) {
                table.backgroundColor = [UIColor clearColor];

}else if (idx==1){
                table.backgroundColor = [UIColor colorWithHexString:@"e2e2e5"];

}else{
                table.backgroundColor = [UIColor colorWithHexString:@"d7d7d7"];

}
            table.tableFooterView = [UIView new];
        }];
        bgView = [[UIView alloc] init];
        bgView.backgroundColor = [UIColor colorWithRed:.0f green:.0f blue:.0f alpha:.3f];
        bgView.userInteractionEnabled = YES;
        [bgView addSubview:[tables objectAtIndex:0] ];
         bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight);
                 [self addSubview:bgView];

         [self loadSels];
    [self adjustTableViews];
    UISwipeGestureRecognizer *swipe2 =[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
swipe2.direction =UISwipeGestureRecognizerDirectionRight;
[self addGestureRecognizer:swipe2];

        
    }
    return self;
}
-(void)viewDidLayoutSubviews

{[tables enumerateObjectsUsingBlock:^(UITableView *table, NSUInteger idx, BOOL *stop) {
if ([table respondsToSelector:@selector(setSeparatorInset:)]) {

        [table setSeparatorInset:UIEdgeInsetsZero];

    }

 

    if ([table respondsToSelector:@selector(setLayoutMargins:)]) {

        [table setLayoutMargins:UIEdgeInsetsZero];

    }


}];

    

}



-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{

    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {

        [cell setSeparatorInset:UIEdgeInsetsZero];

    }

 

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {

        [cell setLayoutMargins:UIEdgeInsetsZero];

    }

 

}
-(void)swipeAction:(UISwipeGestureRecognizer *)swipe
{
    UITableView *t0 = [tables objectAtIndex:0];
    UITableView *t1 = [tables objectAtIndex:1];
    UITableView *t2 = [tables objectAtIndex:2];
//NSLog(@"扫一下");
if (swipe.direction ==UISwipeGestureRecognizerDirectionRight)       {
    NSLog(@"右清扫");
     if(t2.superview)
     {
       _secondselIndex = nil;
       [t1 reloadData];
       [t2 removeFromSuperview];
       [self saveSels];
       [self adjustTableViews];
            }
     else if (t1.superview){
      _firstselIndex = nil;
      [t0 reloadData];
      [t1 removeFromSuperview];
      [self saveSels];
      [self adjustTableViews];

            }

 }

}


#pragma mark private
/**
 *  调整表视图的位置、大小
 */
- (void)adjustTableViews{
    int w = SCREEN_WIDTH;
    int __block showTableCount = 0;
    [tables enumerateObjectsUsingBlock:^(UITableView *t, NSUInteger idx, BOOL *stop) {
        CGRect rect = t.frame;
        rect.size.height = SCREEN_HEIGHT-kTopHeight - bgView.frame.origin.y;
// rect.size.height = SCREEN_HEIGHT-kTopHeight;

        t.frame = rect;
        if(t.superview)
            ++showTableCount;
    }];
    
    for(int i=0; i!=showTableCount; ++i){
        UITableView *t = [tables objectAtIndex:i];
        CGRect f = t.frame;

        f.size.width =(w) / showTableCount;


if (i==1&&showTableCount==2) {
            f.origin.x = 60;
                        f.size.width =(SCREEN_WIDTH-60);

}
else if (i==1&&showTableCount==3)
{
            f.origin.x = 60;
            f.size.width =(SCREEN_WIDTH-60)/2;

}
else if (i==2&&showTableCount==3)
{
            f.origin.x =(SCREEN_WIDTH-60)/2+60;
            f.size.width =(SCREEN_WIDTH-60)/2;

}

else{
 
        f.origin.x = f.size.width * i;
        }
        t.height =SCREEN_HEIGHT-kTopHeight;
        t.frame = f;
    }
    
}
/**
 *  取消选择
 */
- (void)cancel{
    [self dismiss];
    if([self.delegate respondsToSelector:@selector(assciationMenuViewCancel)]) {
        [self.delegate assciationMenuViewCancel];
    }
}

/**
 *  保存table选中项
 */
- (void)saveSels{
    [tables enumerateObjectsUsingBlock:^(UITableView *t, NSUInteger idx, BOOL *stop) {
        sels[idx] = t.superview ? t.indexPathForSelectedRow.row : -1;
    }];
}

/**
 *  加载保存的选中项
 */
- (void)loadSels{
    [tables enumerateObjectsUsingBlock:^(UITableView *t, NSUInteger i, BOOL *stop) {
        [t selectRowAtIndexPath:[NSIndexPath indexPathForRow:sels[i] inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
        if((sels[i] != -1 && !t.superview) || !i) {
            [bgView addSubview:t];
        }
    }];
}

#pragma mark public
- (void)setSelectIndexForClass1:(NSInteger)idx_1 class2:(NSInteger)idx_2 class3:(NSInteger)idx_3 {
    sels[0] = idx_1;
    sels[1] = idx_2;
    sels[2] = idx_3;
}

- (void)showAsDrawDownView:(UIView *)view {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    CGRect showFrame = view.frame;
    showFrame = [view.superview convertRect:showFrame toView:window];
    CGFloat x = 0.f;
    CGFloat y = showFrame.origin.y+showFrame.size.height;
    CGFloat w = SCREEN_WIDTH;
    CGFloat h = SCREEN_HEIGHT-y;
        bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);


//    bgView.frame = CGRectMake(x, y, w, h);
    if(!bgView.superview) {
        [self addSubview:bgView];
    }
    [self loadSels];
    [self adjustTableViews];
    if(!self.superview) {
        [window addSubview:self];
        self.alpha = .0f;
        [UIView animateWithDuration:.25f animations:^{
            self.alpha = 1.0f;
        }];
    }
    [window bringSubviewToFront:self];
}

- (void)dismiss{
    if(self.superview) {
        [UIView animateWithDuration:.25f animations:^{
            self.alpha = .0f;
        } completion:^(BOOL finished) {
            [bgView.subviews enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
                [obj removeFromSuperview];
            }];
            [self removeFromSuperview];
        }];
    }
}

#pragma mark UITableViewDateSourceDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if(tableView == [tables objectAtIndex:0]){
      static NSString *leftidentifier = @"lefCell";
//        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftidentifier];
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头，距离右边有十几像素；
//cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        if (!cell) {
//            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:leftidentifier];
//                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头，距离右边有十几像素；
//       cell.selectionStyle = UITableViewCellSelectionStyleNone;
//
//        }
//    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(60, 12, 20, 20 )];
//        image.image = [UIImage imageNamed:@"二级"];
//        [cell.contentView addSubview:image];
//               cell.backgroundColor = [UIColor colorWithHexString:@"f0eff5"];
//         cell.textLabel.text = [_delegate assciationMenuView:self titleForClass_1:indexPath.row];
//        cell.textLabel.font = [UIFont systemFontOfSize:14];
//        cell.textLabel.textColor = [UIColor colorWithHexString:@"484848"];
////        cell.textLabel.highlightedTextColor = [UIColor orangeColor];
////        [cell setBackgroundColor:[UIColor whiteColor]];
//        return cell;
 firstlevelTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:leftidentifier];
if (cell==nil) {
        cell=[[firstlevelTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:leftidentifier];
    }
    

if (_firstselIndex == indexPath ) {
        cell.image2.hidden = NO;
    }else {
cell.image2.hidden = YES;

    }
    NSArray *array = _dic[@"oneLevelCategoryList"];
    NSMutableArray *array1 = [NSMutableArray array];
    for (NSDictionary *dic in array) {
    [array1 addObject:dic[@"ctgName"]];
}
  cell.imagestring = _array[indexPath.row];
    cell.string = array1[indexPath.row];
    NSString *string = [_delegate assciationMenuView:self titleForClass_1:indexPath.row];
    return cell;
  
    }else if(tableView == [tables objectAtIndex:1]){
     static NSString *mididentifier = @"midCell";
      twolevelTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:mididentifier];
if (cell==nil) {
        cell=[[twolevelTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mididentifier];
    }
    

if (_secondselIndex == indexPath ) {
        cell.image2.hidden = NO;
            cell.accessoryType = UITableViewCellAccessoryNone;//cell的右边有一个小箭头，距离右边有十几像素；

    }else {
cell.image2.hidden = YES;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
        NSArray *array = _dic[@"oneLevelCategoryList"];
NSDictionary *dic = array[_firstselIndex.row];
NSArray *array2 = dic[@"twoLevelCategoryList"];
 NSMutableArray *arraytitle2 = [NSMutableArray array];
    for (NSDictionary *dic in array2) {
    [arraytitle2 addObject:dic[@"ctgName"]];
}
    cell.string = arraytitle2[indexPath.row];

   NSString *string = [_delegate assciationMenuView:self titleForClass_1:_firstselIndex.row class_2:indexPath.row];
    return cell;
 
        
        return cell;
    }else if(tableView == [tables objectAtIndex:2]){
     static NSString *rightidentifier = @"rightCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:rightidentifier];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头，距离右边有十几像素；
cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:rightidentifier];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头，距离右边有十几像素；
cell.selectionStyle = UITableViewCellSelectionStyleNone;

        }
         UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(-20, 12, 20, 20 )];
        image.image = [UIImage imageNamed:@"三级"];
        [cell.contentView addSubview:image];
             NSArray *array = _dic[@"oneLevelCategoryList"];
NSDictionary *dic = array[_firstselIndex.row];
NSArray *array2 = dic[@"twoLevelCategoryList"];
NSDictionary *dic2 = array2[_secondselIndex.row];
NSArray *array3 = dic2[@"threeLevelCategoryList"];
NSMutableArray *arraytitle3 = [NSMutableArray array];
    for (NSDictionary *dic in array3) {
    [arraytitle3 addObject:dic[@"ctgName"]];
}
cell.textLabel.text =arraytitle3[indexPath.row];
       NSString *string = [_delegate assciationMenuView:self titleForClass_1:_firstselIndex.row class_2:_secondselIndex.row class_3:indexPath.row];
            cell.backgroundColor = [UIColor colorWithHexString:@"d7d7d7"];

        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = [UIColor colorWithHexString:@"484848"];
//        cell.textLabel.highlightedTextColor = [UIColor orangeColor];
//        [cell setBackgroundColor:[UIColor whiteColor]];
        return cell;
    }else{
    
            return nil;

    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger __block count;
//    [tables enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        if(obj == tableView) {
//            count = [_delegate assciationMenuView:self countForClass:idx];
//            *stop = YES;
//        }
//    }];
//    return count;
  NSArray *array = _dic[@"oneLevelCategoryList"];
NSDictionary *dic = array[_firstselIndex.row];


if (tableView == [tables objectAtIndex:0]) {
    return array.count;
}else if(tableView == [tables objectAtIndex:1]){
NSArray *array2 = dic[@"twoLevelCategoryList"];
return array2.count;
}else{
NSArray *array2 = dic[@"twoLevelCategoryList"];
NSDictionary *dic2 = array2[_secondselIndex.row];
NSArray *array3 = dic2[@"threeLevelCategoryList"];

return array3.count;
}
}

#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableView *t0 = [tables objectAtIndex:0];
    UITableView *t1 = [tables objectAtIndex:1];
    UITableView *t2 = [tables objectAtIndex:2];
    BOOL isNexClass = true;
    if(tableView == t0){
    _firstselIndex =  [indexPath copy];
//     firstlevelTableViewCell *oldCell = [t0 cellForRowAtIndexPath:_firstselIndex];
//     oldCell.image.hidden = NO;
     [t0 reloadData];
_firstselIndex = indexPath;
        if([self.delegate respondsToSelector:@selector(assciationMenuView:idxChooseInClass1:)]) {
            isNexClass = [_delegate assciationMenuView:self idxChooseInClass1:indexPath.row];
        }
        if(isNexClass) {
        _secondselIndex = nil;
            [t1 reloadData];
            if(!t1.superview) {
                [bgView addSubview:t1];
            }
            if(t2.superview) {
                [t2 removeFromSuperview];
            }
            [self adjustTableViews];
        }else{
            if(t1.superview) {
                [t1 removeFromSuperview];
            }
            if(t2.superview) {
                [t2 removeFromSuperview];
            }
            [self saveSels];
            [self dismiss];
        }
    }else if(tableView == t1) {
        _secondselIndex =  [indexPath copy];
_secondselIndex = indexPath;
     [t1 reloadData];
        if([self.delegate respondsToSelector:@selector(assciationMenuView:idxChooseInClass1:class2:)]) {
            isNexClass = [_delegate assciationMenuView:self idxChooseInClass1:_firstselIndex.row class2:indexPath.row];
        }
        if(isNexClass){
            [t2 reloadData];
            if(!t2.superview) {
                [bgView addSubview:t2];
            }
            [self adjustTableViews];
        }else{
            if(t2.superview) {
                [t2 removeFromSuperview];
            }
            [self saveSels];
            [self dismiss];
        }
    }else if(tableView == t2) {
        if([self.delegate respondsToSelector:@selector(assciationMenuView:idxChooseInClass1:class2:class3:)]) {
            isNexClass = [_delegate assciationMenuView:self idxChooseInClass1:_firstselIndex.row class2:_secondselIndex.row class3:indexPath.row];
        }
        if(isNexClass) {
            [self saveSels];
//            [self dismiss];
        }
    }
}

@end
